const app = getApp()
import {
  genTestUserSig
} from '../../debug/GenerateTestUserSig'
import {
  change_info
} from "../../test"
Page({

  data: {
    scene: null,
    tourl: '',
    to_id: '',//推荐人id
    check_aunt: false,
    is_share: false, //是否可以绑定推荐人
    aunt_id: '',
    is_oneself: '',
    q: '', //柜子扫码链接
    device_number: '', //柜子编号
    laundry_number: '', //洗衣柜
    roomId: '', //小程序直播房间号
    coffee_number: '', //咖啡柜
    q_to_url: '', //跳转链接
    scan_order_code: '', //雇主扫描阿姨订单二维码
  },

  onLoad(options) {
    if (options.q) {
      let q = decodeURIComponent(options.q);
      this.q_val(q, 'device_number');
      this.q_val(q, 'laundry_number');
      this.q_val(q, 'coffee_number');
      this.q_val(q, 'roomId');
      this.q_val(q, 'q_to_url');
      this.q_val(q, 'scan_order_code')
      this.q_val(q, '/q/');
    }
    let new_device_number = this.data.device_number || this.data.laundry_number || this.data.coffee_number;
    if (new_device_number) {
      get_device_type(new_device_number).then(data => {
        this.setData({
          device_number: '',
          laundry_number: '',
          coffee_number: '',
        })
        // 设备类型 1 = 咖啡柜 2 = 振兴柜 3 = 洗衣柜
        if (data == 1) {
          this.setData({
            coffee_number: new_device_number,
          })
        }
        if (data == 2) {
          this.setData({
            device_number: new_device_number,
          })
        }
        if (data == 3) {
          this.setData({
            laundry_number: new_device_number,
          })
        }
      })
    }
    if (options.scene) {
      this.setData({
        scene: decodeURIComponent(options.scene)
      })
    }
    if (options.is_share) {
      this.setData({
        is_share: true
      })
    }
    if (options.to_id) {
      this.setData({
        to_id: options.to_id
      })
    }
    if (options.tourl) {
      this.setData({
        tourl: decodeURIComponent(options.tourl)
      })
    }
    if (options.is_oneself) {
      this.setData({
        is_oneself: decodeURIComponent(options.is_oneself)
      })
    }
    if (options.check_aunt) {
      this.setData({
        check_aunt: true
      })
    }
    if (options.aunt_id) {
      this.setData({
        aunt_id: options.aunt_id
      })
    }
    wx.login({
      success: (res) => {
        console.log(res.code)
        //   return
        getApp().globalData.post({
          url: '/api/applet.login/getwxinfo.html',
          data: {
            js_code: res.code,
            form_id:this.data.to_id
          }
        }, true).then(r => {
          let data = r.data.data
          wx.setStorageSync('jz_getSessionKey', data.session_key)
          if (r.data.code == 0) {
            getApp().showModal(r.data.msg).then(() => {
              wx.exitMiniProgram()
            })
            return
          }
          if (data.userinfo.status == -1) {
            getApp().showModal(r.data.msg).then(() => {
              wx.exitMiniProgram()
            })
            return
          }
          wx.setStorageSync("userInfo", data.userinfo);
          if (getApp().globalData.envVersion != "release") {
            change_info()
          }
          app.handleTcp()
          // app.blockchain()  //区块链
          app.applettab()
          app.appletpayves()

          // im登陆
          const userID = "JZ_" + data.userinfo.id;
          const userSig = genTestUserSig(userID).userSig;
          app.globalData.userInfo = {
            userSig,
            userID,
          }
          let promise = wx.$TUIKit.login({
            userID: userID,
            userSig: userSig
          });
          promise.then(function (imResponse) {
            console.log(imResponse.data); // 登录成功
            if (imResponse.data.repeatLogin === true) {
              // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
              console.log(imResponse.data.errorInfo);
            }
          }).catch(function (imError) {
            console.warn('login error:', imError); // 登录失败的相关信息
          });

          if (data.userinfo.login_out == 2) {
            wx.reLaunch({
              url: './login_out',
            })
            return
          }

          if (this.data.tourl) {
            wx.reLaunch({
              url: this.data.tourl
            })
          } else {
            wx.reLaunch({
              url: '/pages/index/index'
            })
          }

        })
      }
    })
  },

  q_val(q, val) {
    if (val == '/q/') {
      if (q.split(val).length == 2) {
        let coffee_number = 'CYXF_' + q.split(val)[1];
        this.setData({
          coffee_number
        })
      }
      return
    }
    let arr = q.split(val + "=");
    if (arr.length == 2) {
      this.setData({
        [val]: arr[1]
      })
    }
  },

  IsAyi() {
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'IsAyi',
          uid: wx.getStorageSync('userInfo').id,
          phone: wx.getStorageSync('userInfo').phonenumber,
          id: this.data.aunt_id
        }
      }).then((res => {
        if (res.data.code == 1) {
          reslove()
        } else {
          reject()
        }
      }))
    })
  },

  GetIndexInfo(id = '') {
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'GetIndexInfo',
          uid: id, //分享进来的id
          uid2: wx.getStorageSync('userInfo').id, //自己的id
        }
      }).then(r => {
        if (r.data.result.is_partner) {
          wx.setStorageSync('share_partner_name', r.data.result.index_name + ' · 超有幸福')
          wx.setStorageSync('my_partner_name', r.data.result.index_name)
          reslove()
        } else {
          reslove()
        }
      })
    })
  },
  getShareToPeople() {
    // 阿姨分享
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'ShareToPeople',
          scene: this.data.scene,
          uid: wx.getStorageSync('userInfo').id
        }
      }).then(res => {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
        this.GetIndexInfo(res.data.share_id).then(s => {
          reslove()
        })
      })
    })
  },
  getShare() {
    //分享卡片
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'ShareRec',
          rec_id: this.data.to_id,
          uid: wx.getStorageSync('userInfo').id
        }
      }).then(res => {
        this.GetIndexInfo(this.data.to_id).then(s => {
          reslove()
        })
      })
    })
  },
  id_judge() {
    return new Promise((reslove, reject) => {
      if (!app.globalData.id_judge) {
        // 首次进入
        app.globalData.post({
          data: {
            do: 'Precedence',
            uid: wx.getStorageSync('userInfo').id,
            a: 'wxapp2'
          }
        }).then(res => {
          app.globalData.id_judge = true;
          let type = res.data.data.type;
          let url = res.data.data.url;
          // type:1=用户,2=阿姨,3=商家,4=企业,5=个人
          if (type == 1) {
            wx.reLaunch({
              url: './index',
            })
          } else if (type == 2) {
            app.globalData.post({
              data: {
                do: 'UserSwitch',
                uid: wx.getStorageSync('userInfo').id
              }
            }).then(s => {
              if (s.data.status != 1) {
                wx.reLaunch({
                  url: './index',
                })
              } else {
                app.globalData.post({
                  data: {
                    do: 'housekeeperInfo',
                    uid: s.data.data
                  }
                }).then(r => {
                  wx.setStorageSync('auntInfo', r.data.data)
                  wx.reLaunch({
                    url: '/aunt/pages/index/index',
                  })
                })
              }
            })
          } else if (type == 3) {
            getApp().globalData.posts('/mer/login_v1', {
              "openid": wx.getStorageSync('userInfo').openid
            }).then(res => {
              wx.setStorageSync('merchant', res.data.data)
              wx.setStorageSync('jz_getOpenId', res.data.data.token)
              if (url) {
                wx.reLaunch({
                  url
                })
              } else {
                wx.reLaunch({
                  url: '/merchant/pages/index/blank',
                })
              }
            })
          } else if (type == 4) {
            wx.reLaunch({
              url: '/partner/home?partner_type=2',
            })
          } else if (type == 5) {
            wx.reLaunch({
              url: '/partner/home?partner_type=1',
            })
          } else {
            wx.reLaunch({
              url: './index',
            })
          }
        })
      } else {
        reslove()
      }
    })
  },

  getPhoneNumber(e) {
    getApp().globalData.post({
      url: '/api/applet.login/getphonenumber.html',
      data: {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      }
    }, true).then(r => {
      let data = r.data.data
      wx.setStorageSync("userInfo", data.userinfo);
      getApp().updwxinfo({
        name: '大队长啊'
      })
    })
  },

})